package com.fc.h5dispaly.h5display.ggBook.socket.messenger;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import static com.fc.h5dispaly.h5display.ggBook.socket.messenger.MessengerActivity.MSG_FROM_SERVICE;
/**
 *		劣势：  1、如果有大量的消息同时发送到服务端，服务端也只能一个个处理，不适合并发场景
 * 				2、Messenger主要是为了传递消息，很多时候我们需要的是跨进程调用服务端的方法，不适用于这种场景
 */
public class MessengerService  extends Service {
    private static final String TAG = "MessengerService";
    private final Messenger mMessenger = new Messenger(new MessengerHandler());
    public static final int MSG_FROM_CLIENT = 0;


    private static class MessengerHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_FROM_CLIENT:
                    Log.i(TAG, "receive msg from Client:" + msg.getData().getString("msg"));
                    Messenger client = msg.replyTo;//服务端接收到客户端用来发送消息的 messenger
                    Message replyMessage = Message.obtain(null,MSG_FROM_SERVICE);
                    Bundle bundle = new Bundle();
                    bundle.putString("reply","我是服务端，客户端的消息已经收到");
                    replyMessage.setData(bundle);
                    try {
                        client.send(replyMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                    default:
                        super.handleMessage(msg);
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 客户端可以拿到这个Binder和服务端通讯
        return mMessenger.getBinder();
    }
}
